package ferp.center.server.servlet.bid;

import ferp.center.network.response.ResponseBidDataGet;
import ferp.center.server.Action;
import ferp.center.server.entity.Bid;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * User: igorgok
 * Date: 12/6/12 3:49 PM
 */
public class BidDataGet extends HttpServlet
{
  protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    Action.execute(request, response, Void.class, new Action.Read<Void, ResponseBidDataGet>()
    {
      @SuppressWarnings("unchecked")
      public ResponseBidDataGet run(EntityManager em, Void input) throws IOException
      {
        int start = Integer.valueOf(request.getParameter("s")), chunk = Integer.valueOf(request.getParameter("c"));

        log("loading " + chunk + " bid records starting from " + start);

        List<Bid> bids = em.createQuery("SELECT b FROM Bid b").setFirstResult(start).setMaxResults(Math.min(MAX_CHUNK, chunk)).getResultList();
        LinkedList<ResponseBidDataGet.Record> list = new LinkedList<ResponseBidDataGet.Record>();

        log("bids loaded: " + bids.size());

        for (Bid b : bids)
        {
          ResponseBidDataGet.Record r = new ResponseBidDataGet.Record();

          r.cards = b.getCards();
          r.hand = b.getHand();
          r.penalty = b.getPenalty();
          r.starting = b.getStartingTricks();
          r.last = b.getLast();
          r.result = b.getResult();

          list.add(r);
        }

        return new ResponseBidDataGet(list);
      }
    });
  }

  private static final int MAX_CHUNK = 1000;
}
